const modalChildBehavior = require('../../../behaviors/modalChildBehavior');
const util = require('../../../utils/util');
Component({
  properties: {
    conditions: {
      type: Array,
      value: []
    },
    popviewIsShow: {
      type: Boolean,
      observer: '_popviewShowChange'
    }
  },
  externalClasses: ['flex-vh-center'],
  data: {
    selecterConditions: []
  },
  behaviors: [ modalChildBehavior ],
  methods: {
    onLoad () {
      
    },
    itemSelect (e) {
      let data = e.detail;
      let typeIndex = data.typeindex;
      let itemIndex = data.itemindex;
      let itemActive = data.item.active;
      let conditions = this.data.selecterConditions;

      conditions[ typeIndex ].options[ itemIndex ].active = !itemActive;
      this.setData({
        selecterConditions: conditions
      })
    },
    onReset () {
      this.removeAllActive();
    },
    onSure () {
      this.setDataSmart({
        conditions: util.deepClone(this.data.selecterConditions)
      });
      
      this.triggerEvent('onSure', {
        selected: this.getSelectedConditions(),
        all: this.data.conditions
      });
    },
    _popviewShowChange (newValue) {
      if (newValue) {
        this.setData({
          selecterConditions: util.deepClone(this.data.conditions)
        })
      }
    },
    removeAllActive() {
      let conditions = this.data.selecterConditions;
      for (let i = 0, len_i = conditions.length; i < len_i; i ++) {
        let options = conditions[ i ].options;
        for (let j = 0, len_j = options.length; j < len_j; j ++) {
          conditions[ i ].options[ j ].active = false;
        }
      }
      this.setData({
        selecterConditions: conditions
      })
      console.log(this.data.conditions);
    },
    getSelectedConditions() {
      let selectedConditions = [];
      let conditions = util.deepClone(this.data.selecterConditions);

      for (let i = 0, len_i = conditions.length; i < len_i; i ++) {

        let selectedObj = conditions[ i ];
        let options = conditions[ i ].options;
        selectedObj.options = [];

        for (let j = 0, len_j = options.length; j < len_j; j ++) {
          let item = options[ j ];
          if ( item.active ) {
            selectedObj.options.push(item);
          }
        }
        if ( selectedObj.options.length ) {
          selectedConditions.push(selectedObj);
        }
      }
      return selectedConditions;
    }
  }
}) 